package com.dwd.user.controller;

import com.dwd.basic.utils.AjaxResult;
import com.dwd.basic.utils.HttpClientUtils;
import com.dwd.user.constant.WeChatConstant;
import com.dwd.user.pojo.dto.LoginInfoDto;
import com.dwd.user.service.IWeChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

/**
 * @Description: TODO
 * @Author 汶狄
 * @Date 2021/1/19 12:30
 * @Version 1.0
 */
@Controller
@RequestMapping("/wechat")
public class WeChatController {
    @Autowired
    private IWeChatService weChatService;

    /**
     * 拉取二维码
     *
     * @return
     */
    @RequestMapping("/toLogin")
    public String toLogin() {
        //获取code的url，会返回一个code
        String codeUrl = WeChatConstant.CODE_URL.replace("APPID", WeChatConstant.APPID)
                .replace("REDIRECT_URI", WeChatConstant.REDIRECT_URI)
                .replace("SCOPE", WeChatConstant.SCOPE);
        return "redirect:" + codeUrl;
    }

    /**
     * 返回界面，携带授权码
     *
     * @param code
     * @return
     */
    @RequestMapping("/callback")
    public String callback(String code) {
        return "redirect:http://localhost:8002/callback.html?code=" + code;
    }

    /**
     * 处理回调函数
     *
     * @param
     * @return
     */
    @PostMapping("/handlCallback")
    @ResponseBody
    public AjaxResult handlCallback(@RequestBody Map<String, String> param) {
        //通过code获取access_token
        try {
            Map<String, Object> map = weChatService.handlCallback(param.get("code"));
            return AjaxResult.me().setResultObj(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.getMessage());
        }
    }

    /**
     * 微信登陆绑定手机
     * @param loginInfoDto
     * @return
     */
    @PostMapping("/binder")
    @ResponseBody
    public AjaxResult binder(@RequestBody LoginInfoDto loginInfoDto) {
        try {
            Map<String, Object> map = weChatService.binder(loginInfoDto);
            return AjaxResult.me().setResultObj(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.getMessage());
        }
    }
}
